package com.css.action;

import java.util.List;
import java.util.Map;

import com.css.service.IUsersService;
import com.css.vo.Users;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UsersAction extends ActionSupport {
	private Users users;
	private IUsersService usersService;
	private List<Users> usersList; // 查询结果
	private Map request;

	public Map getRequest() {
		return request;
	}

	public void setRequest(Map request) {
		this.request = request;
	}

	public Users getUsers() {
		return users;
	}

	public List<Users> getUsersList() {
		return usersList;
	}

	public void setUsersList(List<Users> usersList) {
		this.usersList = usersList;
	}

	public void setUsers(Users users) {
		this.users = users;
	}

	public IUsersService getUsersService() {
		return usersService;
	}

	public void setUsersService(IUsersService usersService) {
		this.usersService = usersService;
	}

	public String execute() throws Exception {
		return SUCCESS;
	}

	public String register() throws Exception {
		if (usersService.existUsers(users.getUserName())) {
			return ERROR;
		}
		users.setIsAdmin(false);
		usersService.saveUsers(users);
		return SUCCESS;
	}

	public String login() throws Exception {
		if (usersService
				.validateUsers(users.getUserName(), users.getPassword())) {
			usersList = usersService.getUserList(); // 通过服务查询数据
			request = (Map) ActionContext.getContext().get("request");
			request.put("usersList", usersList);
			System.out.println(usersList);
			return SUCCESS;
		}

		return ERROR;
	}

	public String delUser() throws Exception {
		Users re = usersService.getUsersById(users.getUserId());
		if (re != null) {
			usersService.delUserById(users.getUserId());
			usersList = usersService.getUserList(); // 通过服务查询数据
			request = (Map) ActionContext.getContext().get("request");
			request.put("usersList", usersList);
			return SUCCESS;
		}
		return ERROR;
	}

	public String updateUser() throws Exception {

		if (users != null) {
			usersService.updateUser(users);
			usersList = usersService.getUserList(); // 通过服务查询数据
			request = (Map) ActionContext.getContext().get("request");
			request.put("usersList", usersList);
			return SUCCESS;
		}
		return ERROR;
	}

	public String getList() throws Exception {
		if (usersList != null) {
			request = (Map) ActionContext.getContext().get("request");
			request.put("usersList", usersList);
			return SUCCESS;
		}
		usersList = usersService.getUserList(); // 通过服务查询数据
		request = (Map) ActionContext.getContext().get("request");
		request.put("usersList", usersList);
		return SUCCESS;
	}

	public String getUsersByName() throws Exception {
		usersList = usersService.getUsersByName(users.getUserName());
		if (usersList != null) {
			request = (Map) ActionContext.getContext().get("request");
			request.put("usersList", usersList);
			return SUCCESS;
		}
		return ERROR;
	}

}
